package com.ys.load.util;

import java.io.File;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;

import lombok.extern.slf4j.Slf4j;

/**
 * 定时任务
 * @author yusong
 * @date 20241120
 */
@Configuration
@EnableScheduling
@Slf4j
public class DownloadBooksTask {
	
	@Value("${wechat.pay.imageUrl}")
	private String imageUrl;
	
	/**
	 * 测试 每5秒执行一次
	 */
	//@Scheduled(cron = "0/5 * * * * ?")
	private void test() {
		//System.out.println("-------------------------------------------------" + imageUrl);
	}
	
	/**
	 * 定时删除图片 2个小时执行一次
	 * 3fb069233c244498969c4ae0662173dd-1731914739419
	 */
	@Scheduled(cron = "0 0 */2 * * ?")
	private void deleteImg() {
		
		File folder = new File(imageUrl);
		File[] files = folder.listFiles(); 
		
		if (files != null) {
			 for (File file : files) {
				 if (file.isFile()) {
					 
					 String fileName = file.getName();
					 Long time = Long.valueOf(fileName.split("-")[1].split("\\.")[0]);
					 Long timeDifference = System.currentTimeMillis() - time;
					 Integer num = Integer.valueOf(timeDifference/(1000*3600) + "");//生成的二维码的时间 单位(小时)
					 if(num>48) {
						 Path path = Paths.get(imageUrl + fileName);
						 try {
							 Files.delete(path);
							 log.info("删除文件成功");
						 } catch (Exception e) {
							 log.info("文件删除失败: " + e.getMessage());
						 }
					 }
					 
				 }
			 }
		}
	}
	
}

